<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :exclude-values="['nodeName', 'processDefinitionName']"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="processKey" label="流程名称">
          <ProcessName v-model="state.query.processKey" />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="taskDefKey" label="节点名称">
          <!-- <FIAutoSelect
            v-model="state.query.taskDefKey"
            :props="{ value: 'nodeKey', label: 'nodeName' }"
            :display-key="['nodeKey','nodeName']"
            api-url="/bpm-service/BpmProcessDef/queryProcessNode"
            searchParam="nodeKey"
          /> -->
          <TaskName v-model="state.query.taskDefKey" />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="biztypeCode" label="发起业务">
          <FIAutoSelect
            v-model="state.query.biztypeCode"
            :props="{ value: 'biztypeCode', label: 'biztypeName' }"
            :display-key="['biztypeCode', 'biztypeName']"
            api-url="/bpm-service/AppCfg/queryBizType"
            searchParam="biztypeCode"
          />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="configId"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="true"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
      @on-cell-select="selectClick"
      @on-cell-click="beforeSelClick"
    >
      <template #headerBtn>
        <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          beforePopText="请选择一条数据"
          buttonText="删除"
          :btn-binds="{ id: 'delete', border: true }"
          style="margin-right: 10px"
          @confirm="deleteRow"
        />
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIAutoSelect from '@/components/FIAutoSelect/index.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import { ElMessage } from 'element-plus'
import { useMessage, useMessageBox } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import ProcessName from '../../components/ProcessName.vue'
import TaskName from '../../components/TaskName.vue'
import {
  apiQueryAssignee,
  apiQueryUser,
  apiDeleteAuth,
  apiSaveAssignee,
  apiQueryProcessesDef,
  apiQueryProcessNode,
  apiQueryBizType,
  apiQueryRoles,
  apiDeleteAssignee,
} from '@/api/modules/EW.js'
const route = useRoute()
const searchWrapperSpan = 8
const isTableLoading = ref(false)
// 页面编码
const tableId = 'assigneecfg'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const bizTypeArr = ref([])
const taskArr = ref([])
const nodeArr = ref([])
const nodeSearchArr = ref([])
const userList = ref([])
const deptList = ref([])
const userlistCurrent = ref(1)
const nodeCurrent = ref(1)
const bizCurrent = ref(1)
const nodeSearchCurrent = ref(1)
const loadMoreEnd = ref(false)
const loadMorebizEnd = ref(false)
const loadMoreproEnd = ref(false)
const loadMorenodeEnd = ref(false)
const searchNodeEnd = ref(false)
const postList = ref([])
const state = reactive({
  query: {
    processKey: '',
    taskDefKey: '',
    nodeName: '',
    biztypeCode: '',
    processDefinitionName: '',
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})

const columns: Column[] = reactive([
  {
    label: '流程代码',
    prop: 'processKey',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/BpmProcessDef/queryProcessesDef',
        props: { value: 'processDefinitionKey', label: 'processDefinitionKey' },
        displayKey: ['processDefinitionKey', 'processDefinitionName'],
        searchParam: 'processKeyOrName',
      },
    },
  },
  {
    label: '流程名称',
    prop: 'processName',
    align: 'center',
    editable: false,
    editType: 'input',
  },
  {
    label: '节点代码',
    prop: 'taskDefKey',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/ProcInst/queryTask',
        props: { value: 'taskDefKey', label: 'taskName' },
        displayKey: ['taskName'],
        apiParams: {
          current: 1,
          size: 10,
          taskKeyOrName: '',
        },
      },
    },
  },
  {
    label: '节点名称',
    prop: 'taskDefName',
    align: 'center',
    editable: false,
    editType: 'input',
  },
  {
    label: '发起应用',
    prop: 'appCode',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/AppCfg/queryApp',
        props: { value: 'appCode', label: 'appCode' },
        displayKey: ['appCode', 'appName'],
        searchParam: 'appQuery',
      },
    },
  },
  {
    label: '发起模块',
    prop: 'moduleCode',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/AppCfg/queryModule',
        props: { value: 'moduleCode', label: 'moduleCode' },
        displayKey: ['moduleCode', 'moduleName'],
        searchParam: 'moduleQuery',
        apiParams: {
          current: 1,
          size: 10,
          appId: '',
          moduleQuery: '',
        },
      },
    },
  },
  {
    label: '发起业务',
    prop: 'biztypeCode',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/AppCfg/queryBizType',
        props: { value: 'biztypeCode', label: 'biztypeCode' },
        displayKey: ['biztypeCode', 'biztypeName'],
        searchParam: 'biztypeCode',
        apiParams: {
          current: 1,
          size: 10,
          appId: '',
          moduleId: '',
          biztypeCode: '',
        },
      },
    },
  },
  // {
  //   label: '人员',
  //   prop: 'user',
  //   align: 'center',
  //   editType: 'input',
  // },
  {
    label: '人员',
    prop: 'user',
    align: 'center',
    editable: true,
    editType: 'select',
    editConfig: {
      otherBinds: {
        options: userList.value,
        // apiUrl: '/bpm-service/BpmUser/queryUser',
        // props: { value: 'loginName', label: 'userCName' },
        // displayKey: ['loginName', 'userCName'],
        props: { value: 'loginName', label: 'userCName' },
        displayKey: ['loginName', 'userCName'],
        optionsKey: 'data',
      },
    },
  },
  {
    label: '岗位',
    prop: 'post',
    align: 'center',
    width: '200',
    editable: true,
    editType: 'select',
    editConfig: {
      options: postList.value,
      otherBinds: {
        // options: postList.value,
        // // apiUrl: '/bpm-service/BpmUser/queryRoles',
        props: { value: 'roleEName', label: 'roleCName' },
        displayKey: ['roleCName'],
        optionsKey: 'data',
      },
    },
  },

  // {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [{ id: 'isTop', type: 'top' }],
  // },
])

const checkedRows = ref([])
const processArr = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const beforeSelClick = (scope) => {
  console.log(scope, '查看555')
  if (scope.column.property == 'taskDefKey') {
    if (!scope.row.processKey) {
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.disabled = true
    } else {
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.disabled = false
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.apiParams.taskKeyOrName =
        scope.row.processKey
    }
  }
  if (scope.column.property == 'moduleCode') {
    if (!scope.row.appCode) {
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.disabled = true
    } else {
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.disabled = false
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.apiParams.appId = scope.row.appId
    }
  }
  if (scope.column.property == 'biztypeCode') {
    if (!scope.row.moduleCode) {
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.disabled = true
    } else {
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.disabled = false
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.apiParams.moduleId = scope.row.moduleId
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.apiParams.appId = scope.row.appId
    }
  }
}
const selectClick = (scope, item) => {
  // console.log(scope, item, '查看')
  console.log(tableRef.value.cloneColumnList[scope.cellIndex + 1],'pppp')
  if (scope.column.property == 'processKey') {
    tableRef.value.setCellValue(scope.$index, 'processName', item.processDefinitionName)
    // tableRef.value.cloneColumnList[scope.cellIndex + 1].editConfig.otherBinds.apiParams.taskKeyOrName =
    // item.processKey
  }
  if (scope.column.property == 'taskDefKey') {
    tableRef.value.setCellValue(scope.$index, 'taskDefName', item.taskName)
  }
  if (scope.column.property == 'biztypeCode') {
    tableRef.value.setCellValue(scope.$index, 'biztypeName', item.biztypeName)
    tableRef.value.setCellValue(scope.$index, 'biztypeId', item.biztypeId)
  }
  if (scope.column.property == 'appCode') {
    tableRef.value.setCellValue(scope.$index, 'appId', item.appId)
    tableRef.value.setCellValue(scope.$index, 'appCode', item.appCode)
    tableRef.value.setCellValue(scope.$index, 'appName', item.appName)
  }
  if (scope.column.property == 'moduleCode') {
    tableRef.value.setCellValue(scope.$index, 'moduleCode', item.moduleCode)
    tableRef.value.setCellValue(scope.$index, 'moduleId', item.moduleId)
  }
}

//删除事件
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.configId) ids.push(item?.configId)
    })
  isTableLoading.value = true
  apiDeleteAssignee({ configId: ids })
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch((error: any) => {
      useMessage().error(error.data.message)
      isTableLoading.value = false
    })
}
//操作
const actionClick = (item, rowData, btnInfo) => {
  console.log(rowData, 'rowData')
  // useMessageBox()
  //   .confirm(`您确认要置顶吗？`, '提示')
  //   .then(() => {
  //     apiExchangeSortIndex([rowData.id,0])
  //         .then((res) => {
  //           console.log(res, 'res123')
  //           if (res.data.success) {
  //             useMessage().success(res.data.message)
  //             searchFn()
  //           } else {
  //           }
  //         })
  //         .catch((error: any) => {})
  //   })
  //   .catch(() => {})
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiQueryAssignee(state.query)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        // console.log(state.dataList)
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiSaveAssignee(checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
//   const exportRow = () => {
//     apiGroupUserExport(state.query)
//   }
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
const getQueryAll = (processQuery) => {
  let par = {
    processQuery,
    size: 10,
    current: userlistCurrent.value,
  }
  apiQueryProcessesDef(par)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        processArr.value = processArr.value.concat(res.data.data.result)
        if (userlistCurrent.value * 10 >= res.data.data.count) {
          loadMoreproEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const getBizType = () => {
  let par = {
    size: 10,
    current: bizCurrent.value,
  }
  apiQueryBizType(par)
    .then((res) => {
      if (res.data.success) {
        bizTypeArr.value = bizTypeArr.value.concat(res.data.data.result)
        if (bizCurrent.value * 10 >= res.data.data.count) {
          loadMorebizEnd.value = true
        }
      }
    })
    .catch((error: any) => {})
}
const getTaskSeach = () => {
  let par = {
    size: 10,
    current: nodeSearchCurrent.value,
  }
  apiQueryProcessNode(par)
    .then((res) => {
      if (res.data.success) {
        nodeSearchArr.value = nodeSearchArr.value.concat(res.data.data.result)
        if (nodeSearchCurrent.value * 10 >= res.data.data.count) {
          searchNodeEnd.value = true
        }
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {})
}
const getTask = (processKey) => {
  let par = {
    size: 10,
    current: nodeCurrent.value,
    processKey,
  }
  apiQueryProcessNode(par)
    .then((res) => {
      if (res.data.success) {
        nodeArr.value = nodeArr.value.concat(res.data.data.result)
        if (nodeCurrent.value * 10 >= res.data.data.count) {
          loadMorenodeEnd.value = true
        }
      } else {
        ElMessage.error(res.data.message)
      }
      console.log(nodeArr, 'nodeArr')
    })
    .catch((error: any) => {})
}
const getQueryUser = () => {
  apiQueryUser()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        userList.value = res.data.data
        tableRef.value.cloneColumnList.forEach((v) => {
          if (v.prop == 'user') {
            v.editConfig.otherBinds.options = userList
          }
        })
      }
    })
    .catch((error: any) => {})
}
const getPostList = () => {
  let par = {
    current: 1,
    size: 999,
  }
  apiQueryRoles(par)
    .then((res) => {
      if (res.data.success) {
        postList.value = res.data.data
        // postList.value = res.data.data.map((v) => {
        //     return {
        //         label: v.roleCName,
        //         value: v.roleEName,
        //     }
        //     })
        tableRef.value.cloneColumnList.forEach((v) => {
          if (v.prop == 'post') {
            // v.editConfig.otherBinds.options = postList
            v.editConfig.options = postList.value
          }
        })
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}

onMounted(() => {
  getQueryUser()
  getQueryAll('') //查询流程名称
  getTaskSeach() //获取节点数据
  getBizType() //获取发起业务数据
  getPostList()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  // if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
